package com.rtx.wms.customer.k3.down;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.model.field.po.PlFieldMapping;
import com.rtx.edi.platform.field.service.PlFieldMappingService;
import com.rtx.wms.std.handler.so.down.AbstractOrdersDownHandler;
import com.rtx.wms.std.so.bean.ApiOrders;

@Component
public class K3OrdersCreate extends AbstractOrdersDownHandler{
	
	@Autowired
	PlFieldMappingService plFieldMappingService;

	@Override
	protected ApiOrders preHandle(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 订单类型匹配
	 * 根据plFieldMapping表查询匹配的订单类型
	 */
	@Override
	protected void preinsert(ApiOrders o, HttpServletRequest request) {
		ApiMappingInfoBo bo = (ApiMappingInfoBo) request.getAttribute("config");
		
		//映射订单类型&订单来源
		handelOrderTypeAndSource(o,bo);
	}
	
	/**
	 * 映射订单类型
	 * 映射订单来源
	 * @param o
	 * @param bo
	 */
	void handelOrderTypeAndSource(ApiOrders o,ApiMappingInfoBo bo){
		String typemapping = bo.getTypemapping();
		if(StringUtils.hasLength(typemapping)) {
			String k3type = o.getRtxbsart();
			LambdaQueryWrapper<PlFieldMapping> qw = Wrappers.lambdaQuery();
			String wmstype = o.getType();
			
			qw.eq(PlFieldMapping::getCode, typemapping);
			qw.eq(PlFieldMapping::getUdf1, "SO");
			qw.eq(PlFieldMapping::getSource, k3type);
			List<PlFieldMapping> list =	plFieldMappingService.queryByCondition("ris_edi", qw);
			if(list == null || list.size() < 1) {
				throw new RuntimeException("上游系统单据类型-"+k3type+"-在edi-pl_field_mapping-单据类型匹配关系-"+typemapping+"-未维护");
			}
			
			if(!StringUtils.hasLength(list.get(0).getTarget())) {
				wmstype = list.get(0).getTarget();
			};
			
			o.setType(wmstype);
			
			
			if(!StringUtils.hasLength(list.get(0).getUdf1())) {
				o.setType(list.get(0).getUdf1());
			}
		}
	}

	@Override
	protected void validationSpecific(ApiOrders apiOrders) {
		
	}

	@Override
	protected void afterHandle(ApiOrders apiOrders, String requestStr) {
		
	}

}
